﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyMainSite.Models;
using DotNetX;

namespace MyMainSite.Controllers
{
    [HandleError]
    public class BlogController : Controller
    {
        public ActionResult Index(string blogFriendlyUrl, string title)
        {
            RichardsSiteEntities context = new RichardsSiteEntities();

            if (String.IsNullOrEmpty(blogFriendlyUrl))
            {
				return this.RedirectToAction("date", new { year = DateTime.Now.Year.ToString() });
            }

            BlogIndexModel m = new BlogIndexModel(blogFriendlyUrl, title);

            m.CurrentController = "Blog";

            if (!String.IsNullOrEmpty(m.CurrentFriendlyUrl))
            {
                m.BlogEntries = (from e in context.BlogEntries
                                 where e.FriendlyUrl.Trim().ToLower() == m.CurrentFriendlyUrl.Trim().ToLower() &&
                                       e.Blog.FriendlyUrl == m.CurrentBlog.FriendlyUrl
                                 orderby e.DateCreated descending
                                 select e).ToList();

                // there should only be the 1 entry here
                if(m.BlogEntries.Count > 0)
                    m.CurrentTitle = m.BlogEntries[0].Title;
            }
            else
            {
                m.BlogEntries = (from e in context.BlogEntries
                                 where e.Blog.FriendlyUrl == m.CurrentBlog.FriendlyUrl
                                 orderby e.DateCreated descending
                                 select e).ToList();
            }

            return View(m);
        }

        public ActionResult Date(string year, string month)
        {
            RichardsSiteEntities context = new RichardsSiteEntities();

            int y = year.ToInt32OrZero();
            int mo = month.ToInt32OrZero();

            BlogIndexModel m = new BlogIndexModel(y, mo);

            m.CurrentController = "Blog";

            m.BlogEntries = (from e in context.BlogEntries
                             where e.DateCreated.Year == y &&
                                   e.DateCreated.Month == (mo == 0 ? e.DateCreated.Month : mo) // to allow for just year searches
                             orderby e.DateCreated descending
                             select e).ToList();

            return View(m);
        }
    }
}
